package com.scau.bookstore.service.impl;

import com.scau.bookstore.contract.service.CatalogService;
import com.scau.bookstore.common.pojo.Catalog;
import com.scau.bookstore.repository.mapper.CatalogDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CatalogServiceImpl implements CatalogService {

    @Autowired
    private CatalogDao catalogDao;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Catalog> findAll() {
        return catalogDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Catalog> findSearch(Map whereMap, int page, int size) {
        Specification<Catalog> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return catalogDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Catalog> findSearch(Map whereMap) {
        Specification<Catalog> specification = createSpecification(whereMap);
        return catalogDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Catalog findById(Long id) {
        return catalogDao.findById(id).get();
    }

    /**
     * 增加
     *
     * @param catalog
     */
    public void add(Catalog catalog) {
        catalogDao.save(catalog);
    }

    /**
     * 修改
     *
     * @param catalog
     */
    public void update(Catalog catalog) {
        catalogDao.save(catalog);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(Long id) {
        catalogDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Catalog> createSpecification(Map searchMap) {

        return (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            // 分类名称
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                predicateList.add(cb.like(root.get("name").as(String.class), "%" + (String) searchMap.get("name") + "%"));
            }

            return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));

        };

    }

}
